﻿using System.Reflection;
using Dyao.Book.Contract;
using Foundation.Core;

namespace Dyao.Book.Core
{
    public class EnumShortNameSelectResultFilter : ISelectResultFilter, IEnumSelectFilterMetadata
    {
        public void OnCreated(SelectResultContext context)
        {
            if (context.Type == null || !context.Type.IsEnum || !context.Type.FullName.Contains("Dyao.")) return;

            foreach (var item in context.Items)
            {
                if (item is TypeMemberSelectItem memberiItem)
                {
                    var attr = memberiItem.MemberInfo.GetCustomAttribute<ShortNameAttribute>();

                    if (attr != null)
                    {
                        item.Set("shortName", attr.Name);
                    }
                    else
                    {
                        var attributes = memberiItem.MemberInfo.GetCustomAttributes().Where(attr => attr.GetType().FullName.EndsWith("ShortNameAttribute"));

                        if (attributes.Any())
                        {
                            foreach (var attribute in attributes)
                            {
                                var t = attribute.GetType();
                                var np = t.GetProperty("Name");

                                if (np != null && np.CanRead && np.PropertyType == typeof(string))
                                {
                                    var name = np.GetValue(attribute) as string;

                                    item.Set("shortName", name);
                                    break;
                                }
                            }
                        }
                    }
                }
            }
        }
    }
}
